package cn.xzc.job.cocurrent;


import cn.xzc.job.util.ClassUtil;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 用于创建新线程实例的简单的可自定义帮助程序类。提供各种bean属性：线程名称前缀、线程优先级等。
 *
 * @author xzc
 * 当前时间 2024-02-12 21:30:00
 */
public class CustomizableThreadCreator implements Serializable {
    private final AtomicInteger threadCount = new AtomicInteger();
    private String threadNamePrefix;
    private int threadPriority = 5;
    private boolean daemon = false;
    
    private ThreadGroup threadGroup;

    public CustomizableThreadCreator() {
        this.threadNamePrefix = this.getDefaultThreadNamePrefix();
    }

    public CustomizableThreadCreator(
                                     String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix != null ? threadNamePrefix : this.getDefaultThreadNamePrefix();
    }

    public String getThreadNamePrefix() {
        return this.threadNamePrefix;
    }

    public void setThreadNamePrefix(
                                    String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix != null ? threadNamePrefix : this.getDefaultThreadNamePrefix();
    }

    public int getThreadPriority() {
        return this.threadPriority;
    }

    public void setThreadPriority(int threadPriority) {
        this.threadPriority = threadPriority;
    }

    public boolean isDaemon() {
        return this.daemon;
    }

    public void setDaemon(boolean daemon) {
        this.daemon = daemon;
    }

    public void setThreadGroupName(String name) {
        this.threadGroup = new ThreadGroup(name);
    }

    
    public ThreadGroup getThreadGroup() {
        return this.threadGroup;
    }

    public void setThreadGroup(
                               ThreadGroup threadGroup) {
        this.threadGroup = threadGroup;
    }

    public Thread createThread(Runnable runnable) {
        //单线程单独创建：【非创建】
        Thread thread = new Thread(this.getThreadGroup(), runnable, this.nextThreadName());
        thread.setPriority(this.getThreadPriority());
        thread.setDaemon(this.isDaemon());
        return thread;
    }

    protected String nextThreadName() {
        return this.getThreadNamePrefix() + this.threadCount.incrementAndGet();
    }

    protected String getDefaultThreadNamePrefix() {
        return ClassUtil.getShortName(this.getClass()) + "-";
    }
}